import axios from 'axios';

// 获取OSS上传签名
export async function getOssPolicy() {
  const res = await axios.get('/api/oss/policy');
  if (res.data && res.data.code === 0) {
    return res.data.data;
  } else {
    throw new Error(res.data.msg || '获取OSS签名失败');
  }
}

// 上传文件到OSS
export async function uploadToOss(file, policy) {
  const formData = new FormData();
  const filename = Date.now() + '_' + file.name;
  formData.append('key', policy.dir + filename);
  formData.append('policy', policy.policy);
  formData.append('OSSAccessKeyId', policy.accessId);
  formData.append('success_action_status', '200');
  formData.append('signature', policy.signature);
  formData.append('file', file);
  // 可选：自定义回调参数
  if (policy.callback) {
    formData.append('callback', policy.callback);
  }
  await axios.post(policy.host, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
  // 返回完整OSS访问URL
  return policy.host + '/' + policy.dir + filename;
}
